home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 22 / Cream of the Crop 22.iso / program / cgazv4n2.zip / BLOWSTK.C < prev    next >
C/C++ Source or Header  |  1989-08-17  |  2KB  |  76 lines

  1. /**********************************************************************
  2.  * blowstk.c - demonstrate stack overflow checking
  3.  *
  4.  * Author: John Rex
  5.  * Date: July, 1989
  6.  * Compilers: Turbo C 2.0, MSC 5.1
  7.  * Memory model: any
  8.  * Compile time switches:
  9.  *    SAFETY_MARGIN - minimum number of bytes that we are willing to
  10.  *                    leave free on the stack for system interrupts,
  11.  *                    calls to error handling routines, etc.
  12.  *
  13.  * Usage: Just compile and invoke.  It runs a recursive routine to blow
  14.  *        the stack.  The number of successful calls is reported.
  15.  *
  16.  * Sources: This code was derived from study of the Turbo C and Microsoft
  17.  *          C run-time libraries and startup code.
  18.  *
  19.  * Source code and object code may be used freely.
  20.  ********************************************************************/
  21.  
  22. #define SAFETY_MARGIN 500
  23.  
  24. #if defined(__TURBOC__)
  25.     #if defined(__SMALL__) || defined(__MEDIUM__) || defined(__TINY__)
  26.         #define TURBOSMALL
  27.     #else
  28.         #define TURBOLARGE
  29.     #endif
  30. #else
  31.     #define MSC
  32. #endif
  33.  
  34. int count;  /* set to max # of calls we were able to make */
  35.  
  36. void blowstack(int i)
  37. {
  38.     /* stack check protocols */
  39.  
  40. #if defined(TURBOSMALL)
  41.     extern unsigned __brklvl;
  42.  
  43.     if (_SP < (__brklvl + SAFETY_MARGIN)) { /* true if blown */
  44.         count = i;
  45.         return;
  46.     }
  47. #endif
  48.  
  49. #if defined(TURBOLARGE)
  50.     if (_SP < SAFETY_MARGIN) { /* true if blown */
  51.         count = i;
  52.         return;
  53.     }
  54. #endif
  55.  
  56. #if defined(MSC)
  57.     unsigned getsp();
  58.     extern int end;
  59.  
  60.     if ( getsp() < (((unsigned) &end) + SAFETY_MARGIN)) { /* true if blown */
  61.         count = i;
  62.         return;
  63.     }
  64. #endif
  65.  
  66.     /* otherwise, recurse! */
  67.     blowstack(i+1);
  68. }
  69.  
  70. #include <stdio.h>
  71. void main()
  72. {
  73.     blowstack(1);
  74.     printf("Blowstack() made %d calls\n", count);
  75. }
  76.